package org.example.exampreparationtreasure.controller;

import org.example.exampreparationtreasure.common.CommonResultStatus;
import org.example.exampreparationtreasure.model.entity.*;
import org.example.exampreparationtreasure.service.PracticeModeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.example.exampreparationtreasure.util.JwtUtil;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 练习模式控制器
 * 提供四种练习模式的REST接口
 */
@RestController
@RequestMapping("/api/practice")
public class PracticeModeController {

    @Autowired
    private PracticeModeService practiceModeService;
    @Autowired
    private JwtUtil jwtUtil;

    /**
     * 开始章节练习
     */
    @PostMapping("/chapter")
    public ResponseEntity<Map<String, Object>> startChapterPractice(
            @RequestParam Long categoryId,
            @RequestParam(defaultValue = "20") Integer questionCount,
            @RequestParam(defaultValue = "1")  Integer initialDifficulty,
            @RequestHeader(value = "Authorization", required = false) String token) {

        Map<String, Object> body = new HashMap<>();
        try {
            // 处理可选的token参数
            Long userId;
            if (token != null && !token.isEmpty()) {
                userId = jwtUtil.getUserIdByToken(token);
            } else {
                // 测试模式，使用默认用户ID
                userId = 1L;
            }

            ExamPaperConfig config = new ExamPaperConfig();
            config.setMode(PracticeMode.CHAPTER);
            config.setCategoryId(categoryId);
            config.setQuestionCount(questionCount);
            config.setInitialDifficulty(initialDifficulty);

            // 1. 选题
            List<Question> questions = practiceModeService.selectQuestions(config, userId);

            // 2. 保存试卷并创建考试记录
            Long examRecordId = practiceModeService.savePaperAndStartExam(config, userId, questions);

            // 3. 返回考试记录ID和题目
            body.put("success", true);
            body.put("examRecordId", examRecordId);
            body.put("questions", questions);
            body.put("message", "章节练习开始成功");
            return ResponseEntity.ok(body);

        } catch (Exception e) {
            body.put("success", false);
            body.put("code", CommonResultStatus.FAIL.getCode());
            body.put("message", "章节练习开始失败: " + e.getMessage());
            return ResponseEntity.ok(body);
        }
    }

    /**
     * 开始随机练习
     */
    @PostMapping("/random")
    public ResponseEntity<Map<String, Object>> startRandomPractice(
            @RequestParam(defaultValue = "20") Integer questionCount,
            @RequestParam(defaultValue = "1") Integer difficulty,
            @RequestHeader(value = "Authorization", required = false) String token) {

        try {
            // 处理可选的token参数
            Long userId;
            if (token != null && !token.isEmpty()) {
                userId = jwtUtil.getUserIdByToken(token);
            } else {
                // 测试模式，使用默认用户ID
                userId = 1L;
            }

            ExamPaperConfig config = new ExamPaperConfig();
            config.setMode(PracticeMode.RANDOM);
            config.setQuestionCount(questionCount);
            config.setInitialDifficulty(difficulty);

            List<Question> questions = practiceModeService.selectQuestions(config, userId);

            // 保存试卷并创建考试记录
            Long examRecordId = practiceModeService.savePaperAndStartExam(config, userId, questions);

            Map<String, Object> body = new HashMap<>();
            body.put("success", true);
            body.put("examRecordId", examRecordId);
            body.put("questions", questions);
            body.put("message", "随机练习开始成功");
            return ResponseEntity.ok(body);

        } catch (Exception e) {
            Map<String, Object> body = new HashMap<>();
            body.put("success", false);
            body.put("code", CommonResultStatus.FAIL.getCode());
            body.put("message", "随机练习开始失败: " + e.getMessage());
            return ResponseEntity.ok(body);
        }
    }

    /**
     * 开始专项训练
     */
    @PostMapping("/specialized")
    public ResponseEntity<Map<String, Object>> startSpecializedTraining(
            @RequestParam Long categoryId,
            @RequestParam(defaultValue = "20") Integer questionCount,
            @RequestParam(defaultValue = "1") Integer difficulty,
            @RequestHeader(value = "Authorization", required = false) String token) {

        try {
            // 处理可选的token参数
            Long userId;
            if (token != null && !token.isEmpty()) {
                userId = jwtUtil.getUserIdByToken(token);
            } else {
                // 测试模式，使用默认用户ID
                userId = 1L;
            }

            ExamPaperConfig config = new ExamPaperConfig();
            config.setCategoryId(categoryId);
            config.setMode(PracticeMode.SPECIALIZED);
            config.setQuestionCount(questionCount);
            config.setInitialDifficulty(difficulty);

            List<Question> questions = practiceModeService.selectQuestions(config, userId);

            // 保存试卷并创建考试记录
            Long examRecordId = practiceModeService.savePaperAndStartExam(config, userId, questions);

            Map<String, Object> body = new HashMap<>();
            body.put("success", true);
            body.put("examRecordId", examRecordId);
            body.put("questions", questions);
            body.put("message", "专项训练开始成功");
            return ResponseEntity.ok(body);

        } catch (Exception e) {
            Map<String, Object> body = new HashMap<>();
            body.put("success", false);
            body.put("code", CommonResultStatus.FAIL.getCode());
            body.put("message", "专项训练开始失败: " + e.getMessage());
            return ResponseEntity.ok(body);
        }
    }


    /**
     * 开始模拟考试
     */
    @PostMapping("/mock-exam")
    public ResponseEntity<Map<String, Object>> startMockExam(
            @RequestParam Long categoryId,  // 指定考试科目
            @RequestParam(defaultValue = "50") Integer questionCount,
            @RequestParam(defaultValue = "120") Integer timeLimitMinutes,
            @RequestParam(defaultValue = "2") Integer initialDifficulty, // 新增：默认中等难度
            @RequestHeader(value = "Authorization", required = false) String token) {

        try {
            // 处理可选的token参数
            Long userId;
            if (token != null && !token.isEmpty()) {
                userId = jwtUtil.getUserIdByToken(token);
            } else {
                // 测试模式，使用默认用户ID
                userId = 1L;
            }

            ExamPaperConfig config = new ExamPaperConfig();
            config.setMode(PracticeMode.MOCK_EXAM);
            config.setCategoryId(categoryId);
            config.setQuestionCount(questionCount);
            config.setTimeLimitMinutes(timeLimitMinutes);
            config.setInitialDifficulty(initialDifficulty); // 设置难度

            List<Question> questions = practiceModeService.selectQuestions(config, userId);

            // 保存试卷并创建考试记录
            Long examRecordId = practiceModeService.savePaperAndStartExam(config, userId, questions);

            Map<String, Object> examData = new HashMap<>();
            examData.put("examRecordId", examRecordId);
            examData.put("questions", questions);
            examData.put("timeLimit", timeLimitMinutes);
            examData.put("totalQuestions", questions.size());

            Map<String, Object> body = new HashMap<>();
            body.put("success", true);
            body.put("data", examData);
            body.put("message", "模拟考试开始成功");
            return ResponseEntity.ok(body);

        } catch (Exception e) {
            Map<String, Object> body = new HashMap<>();
            body.put("success", false);
            body.put("code", CommonResultStatus.FAIL.getCode());
            body.put("message", "模拟考试开始失败: " + e.getMessage());
            return ResponseEntity.ok(body);
        }
    }

    /**
     * 提交考试答案
     */
    @PostMapping("/submit")
    public ResponseEntity<Map<String, Object>> submitExam(
            @RequestParam Long examRecordId,
            @RequestBody Map<String, Object> submitData,
            @RequestHeader(value = "Authorization", required = false) String token) {

        Map<String, Object> body = new HashMap<>();
        try {
            // 处理可选的token参数
            Long userId;
            if (token != null && !token.isEmpty()) {
                userId = jwtUtil.getUserIdByToken(token);
            } else {
                // 测试模式，使用默认用户ID
                userId = 1L;
            }

            // 从请求体中获取答案数据和考试用时
            @SuppressWarnings("unchecked")
            List<Map<String, Object>> answers = (List<Map<String, Object>>) submitData.get("answers");
            Integer examDuration = (Integer) submitData.get("examDuration");

            // 调用服务层提交考试
            Map<String, Object> result = practiceModeService.submitExam(examRecordId, userId, answers, examDuration);

            body.put("success", true);
            body.put("data", result);
            body.put("message", "考试提交成功");
            return ResponseEntity.ok(body);

        } catch (Exception e) {
            body.put("success", false);
            body.put("code", CommonResultStatus.FAIL.getCode());
            body.put("message", "考试提交失败: " + e.getMessage());
            return ResponseEntity.ok(body);
        }
    }

    

}